package com.mine.modules.vm.service.impl;

import com.mine.common.domain.vo.Result;
import com.mine.common.utils.SpringContextUtils;
import com.mine.modules.sys.entity.SysDictItem;
import com.mine.modules.sys.service.ISysDictItemService;
import com.mine.modules.vm.common.constant.BizConstant;
import com.mine.modules.vm.domain.dto.CommonElementListDto;
import com.mine.modules.vm.domain.dto.QueryElementDto;
import com.mine.modules.vm.service.IVmCommonService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

@Service
@RequiredArgsConstructor
public class VmCommonServiceImpl implements IVmCommonService {

    private static final Logger log = LoggerFactory.getLogger(VmCommonServiceImpl.class);
    private final ISysDictItemService sysDictItemService;

    @Override
    public Result<?> commonElementList(CommonElementListDto commonElementListDto) {
        //通过数据实体查询数据列表
        if (commonElementListDto == null || StringUtils.isBlank(commonElementListDto.getElementType())) {
            return Result.error("参数不完整！");
        }
        //查询数据字典
        SysDictItem sysDictItem = sysDictItemService.lambdaQuery().eq(SysDictItem::getItemValue, commonElementListDto.getElementType()).one();
        if (sysDictItem == null || StringUtils.isBlank(sysDictItem.getExtendService())) {
            return Result.error("数据字典配置不完整！");
        }
        return Result.OK(getListByMethod(commonElementListDto, sysDictItem.getExtendService(), BizConstant.COMMON_ELEMENT_LIST_PAGE_METHOD));
    }

    @Override
    public Object getListByMethod(CommonElementListDto commonElementListDto, String classPath, String method){
        try {
            Class<?> clazzService = Class.forName(classPath);
            Object service = SpringContextUtils.getBean(clazzService);
            Method pageMethod = clazzService.getMethod(method, CommonElementListDto.class);
            return pageMethod.invoke(service, commonElementListDto);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    @Override
    public Object getListByMethod(QueryElementDto queryElementDto, String classPath, String method){
        try {
            Class<?> clazzService = Class.forName(classPath);
            Object service = SpringContextUtils.getBean(clazzService);
            Method pageMethod = clazzService.getMethod(method, QueryElementDto.class);
            return pageMethod.invoke(service, queryElementDto);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

}
